#!/bin/bash
# =================================================================
# 修复 Poppler 依赖库问题
# 用途：复制缺失的 poppler 库并修复 rpath
# =================================================================

set -e

APP_PATH="/Applications/LimeReader.app"
FRAMEWORKS_DIR="$APP_PATH/Contents/Frameworks"

echo ""
echo "=========================================="
echo " 修复 Poppler 依赖库"
echo "=========================================="
echo ""

# 检查应用是否存在
if [ ! -d "$APP_PATH" ]; then
    echo "[ERROR] ❌ 未找到应用程序: $APP_PATH"
    exit 1
fi

# 检查是否有写权限
if [ ! -w "$APP_PATH" ]; then
    echo "[ERROR] ❌ 没有写权限，需要使用 sudo"
    echo "请运行: sudo bash $0"
    exit 1
fi

echo "[STEP 1] 检查当前 poppler 库..."
echo ""
ls -lh "$FRAMEWORKS_DIR"/libpoppler* 2>/dev/null || echo "  (未找到任何 poppler 库)"
echo ""

echo "[STEP 2] 检查依赖关系..."
echo ""
if [ -f "$FRAMEWORKS_DIR/libpoppler-cpp.2.dylib" ]; then
    echo "  libpoppler-cpp.2.dylib 的依赖:"
    otool -L "$FRAMEWORKS_DIR/libpoppler-cpp.2.dylib" | grep poppler
else
    echo "[ERROR] ❌ 未找到 libpoppler-cpp.2.dylib"
    exit 1
fi
echo ""

echo "[STEP 3] 从 Homebrew 复制缺失的 poppler 库..."
echo ""

# 查找 Homebrew 中的 poppler 库
POPPLER_LIB=$(find /opt/homebrew/Cellar/poppler -name "libpoppler.*.dylib" 2>/dev/null | head -1)

if [ -z "$POPPLER_LIB" ]; then
    echo "[ERROR] ❌ 在 Homebrew 中未找到 libpoppler 库"
    echo "请安装: brew install poppler"
    exit 1
fi

echo "  找到: $POPPLER_LIB"
POPPLER_NAME=$(basename "$POPPLER_LIB")
echo "  复制: $POPPLER_NAME"

# 复制库
cp "$POPPLER_LIB" "$FRAMEWORKS_DIR/"

# 同时查找并复制其他可能需要的 poppler 库
for lib in /opt/homebrew/Cellar/poppler/*/lib/libpoppler*.dylib; do
    if [ -f "$lib" ]; then
        LIB_NAME=$(basename "$lib")
        if [ ! -f "$FRAMEWORKS_DIR/$LIB_NAME" ]; then
            echo "  复制: $LIB_NAME"
            cp "$lib" "$FRAMEWORKS_DIR/"
        fi
    fi
done

echo ""
echo "[STEP 4] 修复库的 install name 和 rpath..."
echo ""

# 修复所有 poppler 库的 install name
for lib in "$FRAMEWORKS_DIR"/libpoppler*.dylib; do
    if [ -f "$lib" ]; then
        LIB_NAME=$(basename "$lib")
        echo "  修复: $LIB_NAME"
        
        # 修改 install name 为相对路径
        install_name_tool -id "@rpath/$LIB_NAME" "$lib" 2>/dev/null || true
        
        # 修复库内部的依赖路径
        otool -L "$lib" | grep "libpoppler" | awk '{print $1}' | while read dep; do
            if [[ "$dep" == /opt/homebrew/* ]] || [[ "$dep" == @rpath/* ]]; then
                DEP_NAME=$(basename "$dep")
                echo "    修复依赖: $DEP_NAME"
                install_name_tool -change "$dep" "@rpath/$DEP_NAME" "$lib" 2>/dev/null || true
            fi
        done
    fi
done

echo ""
echo "[STEP 5] 签名新复制的库..."
echo ""

for lib in "$FRAMEWORKS_DIR"/libpoppler*.dylib; do
    if [ -f "$lib" ]; then
        LIB_NAME=$(basename "$lib")
        echo "  签名: $LIB_NAME"
        codesign --force --sign - --timestamp=none "$lib" 2>/dev/null || true
    fi
done

echo ""
echo "[STEP 6] 重新签名主应用..."
echo ""

# 创建临时 entitlements 文件
TEMP_ENTITLEMENTS=$(mktemp /tmp/limereader_entitlements.XXXXXX)
cat > "$TEMP_ENTITLEMENTS" << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.cs.allow-jit</key>
    <true/>
    <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
    <true/>
    <key>com.apple.security.cs.disable-library-validation</key>
    <true/>
</dict>
</plist>
EOF

codesign --force --sign - --timestamp=none --deep --entitlements "$TEMP_ENTITLEMENTS" "$APP_PATH" 2>&1 || true
rm -f "$TEMP_ENTITLEMENTS"

echo ""
echo "[STEP 7] 验证修复结果..."
echo ""

echo "  Frameworks 目录中的 poppler 库:"
ls -lh "$FRAMEWORKS_DIR"/libpoppler* 2>/dev/null
echo ""

echo "  libpoppler-cpp.2.dylib 的依赖关系:"
otool -L "$FRAMEWORKS_DIR/libpoppler-cpp.2.dylib" | grep -E "(poppler|@rpath)"
echo ""

echo ""
echo "=========================================="
echo " 修复完成！"
echo "=========================================="
echo ""
echo "现在可以尝试运行："
echo "  open /Applications/LimeReader.app"
echo ""

